package controllers;

import java.util.Calendar;
import java.util.Date;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

import repository.ItemRepository;
import repository.UserRepository;
import domain.User;

@Controller
public class GeneralController{
	private ItemRepository itemRepository;
	private UserRepository userRepository;
	
	@Autowired
	public GeneralController(ItemRepository itemRepository, UserRepository userRepository){
		this.itemRepository=itemRepository;
		this.userRepository=userRepository;
	}
	
	@SuppressWarnings("deprecation")
	@RequestMapping(method = RequestMethod.GET)
	public String index(HttpSession sess, ModelMap mav) {
		User user;
		user = (User) sess.getAttribute("user");
		
		if (user != null) {
			mav.addObject("user", user);
		}
		
		mav.addObject("lastItems", itemRepository.getLastItems(5));
		mav.addObject("moreVisitedItems", itemRepository.getMoreVisitedItems(5));		
			
		return "general/index";
	}
	
	@SuppressWarnings("deprecation")
	@RequestMapping(method = RequestMethod.POST)
	public String login (HttpServletRequest req,HttpSession sess, @RequestParam("user") String usr, 
			@RequestParam("password") String pass, ModelMap mav) {
		User user = userRepository.validate(usr,pass);

		if (user != null) {
			sess.setAttribute("user", user);
			user.setLastAccess(new Date(Calendar.getInstance().getTime().getTime()));
		} else {
			mav.addObject("errorLogin","Invalid username or password.");
		}
		
		return this.index(sess, mav);
	}	

	@RequestMapping(method = RequestMethod.GET)
	public String logout (HttpSession sess) {
		sess.invalidate();
		return "redirect:/bin/general/index";
	}		
	
	@RequestMapping(method = RequestMethod.GET)
	public ModelAndView error() {
		ModelAndView mav = new ModelAndView();
		mav.addObject("errorTitle", "Internal error");
		mav.addObject("errorMessage", "Server error - Try again later");
		mav.setViewName("general/error");
		return mav;
	}
}